package services

import (
	models "devops-dcc/internal/model"
	"devops-dcc/internal/repositories"
)

type PlatformService struct {
	repo repositories.PlatformRepository
}

func NewPlatformService(repo repositories.PlatformRepository) *PlatformService {
	return &PlatformService{repo: repo}
}

// 平台CRUD
func (s *PlatformService) CreatePlatform(req models.CreatePlatformRequest) (*models.Platform, error) {
	platform := &models.Platform{
		Username:    req.Username,
		Password:    req.Password,
		Address:     req.Address,
		Description: req.Description,
	}
	if err := s.repo.CreatePlatform(platform); err != nil {
		return nil, err
	}
	return platform, nil
}

func (s *PlatformService) GetPlatform(id uint) (*models.Platform, error) {
	return s.repo.GetPlatformByID(id)
}

func (s *PlatformService) GetAllPlatforms() ([]models.Platform, error) {
	return s.repo.GetAllPlatforms()
}

func (s *PlatformService) UpdatePlatform(id uint, req models.UpdatePlatformRequest) (*models.Platform, error) {
	platform, err := s.repo.GetPlatformByID(id)
	if err != nil {
		return nil, err
	}

	if req.Username != "" {
		platform.Username = req.Username
	}
	if req.Address != "" {
		platform.Address = req.Address
	}
	if req.Password != "" {
		platform.Password = req.Password
	}
	platform.Description = req.Description

	if err := s.repo.UpdatePlatform(platform); err != nil {
		return nil, err
	}
	return platform, nil
}

func (s *PlatformService) DeletePlatform(id uint) error {
	return s.repo.DeletePlatform(id)
}

// 环境CRUD
func (s *PlatformService) CreateEnvironment(req models.CreateEnvironmentRequest) (*models.Environment, error) {
	env := &models.Environment{
		EnvName:     req.EnvName,
		Description: req.Description,
	}
	if err := s.repo.CreateEnvironment(env); err != nil {
		return nil, err
	}
	return env, nil
}

func (s *PlatformService) GetEnvironment(id uint) (*models.Environment, error) {
	return s.repo.GetEnvironmentByID(id)
}

func (s *PlatformService) GetAllEnvironments() ([]models.Environment, error) {
	return s.repo.GetAllEnvironments()
}

// 平台环境配置
func (s *PlatformService) SetPlatformEnvConfig(platformID, envID uint, config string) error {
	return s.repo.SetPlatformEnvConfig(platformID, envID, config)
}

func (s *PlatformService) GetPlatformEnvConfig(platformID, envID uint) (*models.PlatformEnvironment, error) {
	return s.repo.GetPlatformEnvConfig(platformID, envID)
}
